// pages/scan/scan.js
import ColorThief from '../../utils/color-thief.js'
import {
  rgbToHex,
  uuid,
  colorsEqual,
  saveBlendent
} from '../../utils/util.js'
const app = getApp()
const STATE_EMPTY = 0;
const STATE_LOADING = 1;
const STATE_SUCCEED = 2;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hd: true,
    repeat: '1',
    address: "",
    array: ['中国文学名著', '外国文学名著', '教材课本资料'],
    tag: '还未输入',
    jia: '还未输入',
    multiArray: [
      ['A架', 'B架', 'C架', 'D架', 'E架'],
      ['第一排', '第二排', '第三排', '第四排', '第五排']
    ],
    imgPath: null,
    imgInfo: {},
    colorCount: 5,
    state: STATE_EMPTY
  },
  bindMultiPickerChange: function (res) {
    console.log('picker发送选择改变，携带值为', res.detail.value[0])
    if (res.detail.value[0] == 0) {
      this.setData({
        jia: 'A架，'
      })
    }
    if (res.detail.value[0] == 1) {
      this.setData({
        jia: 'B架，'
      })
    }
    if (res.detail.value[0] == 2) {
      this.setData({
        jia: 'C架，'
      })
    }
    if (res.detail.value[0] == 3) {
      this.setData({
        jia: 'D架，'
      })
    }

    if (res.detail.value[0] == 4) {
      this.setData({
        jia: 'E架，'
      })
    }
    if (res.detail.value[1] == 0) {
      this.setData({
        row: '第一排'
      })
    }
    if (res.detail.value[1] == 1) {
      this.setData({
        row: '第二排'
      })
    }
    if (res.detail.value[1] == 2) {
      this.setData({
        row: '第三排'
      })
    }
    if (res.detail.value[1] == 3) {
      this.setData({
        row: '第四排'
      })
    }
    if (res.detail.value[1] == 4) {
      this.setData({
        row: '第五排'
      })
    }
  },
  sort: function (res) {
    console.log('picker发送选择改变，携带值为', res.detail.value)
    if (res.detail.value == 0) {
      this.setData({
        tag: '中国文学名著'
      })
    }
    if (res.detail.value == 1) {
      this.setData({
        tag: '外国文学名著'
      })
    }
    if (res.detail.value == 2) {
      this.setData({
        tag: '教材课本资料'
      })
    }
  },

  address: function (res) {
    this.setData({
      address: res.detail.value
    })
  },
  
  scanCode: function (event) {
    var that = this
    wx.scanCode({
      onlyFromCamera: true,
      scanType: ['barCode'],
      success: res => {
        console.log(res);
        wx.showLoading({
          title: '正在加载',
          duration: 1000
        });
        wx.cloud.callFunction({
          name: 'scancode',
          // 传递给云函数的参数
          data: {
            isbn: res.result
          },
          success: res => {
            var bookString = res.result;
            console.log((JSON.parse(bookString)).title)
            console.log(JSON.parse(bookString))
            that.setData({
              hd: false,
              repeat: '2',
              author: (JSON.parse(bookString)).author,
              author_intro: (JSON.parse(bookString)).author_intro,
              catalog: (JSON.parse(bookString)).catalog,
              image: (JSON.parse(bookString)).image,
              isbn: (JSON.parse(bookString)).isbn13,
              pages: (JSON.parse(bookString)).pages,
              price: (JSON.parse(bookString)).price,
              pubdate: (JSON.parse(bookString)).pubdate,
              publisher: (JSON.parse(bookString)).publisher,
              average: (JSON.parse(bookString)).rating.average,
              summary: (JSON.parse(bookString)).summary,
              title: (JSON.parse(bookString)).title,
              translator: (JSON.parse(bookString)).translator,
              imgPath: (JSON.parse(bookString)).image,
            })
            this.chooseImg()
          },
          fail: err => {
            console.error(err)
            wx.showToast({
              icon: 'none',
              title: '扫码失败',
              duration: 1000
            })
          }
        })
      },
      fail: err => {
        console.log(err);
        wx.showToast({
          icon: 'none',
          title: '扫码失败',
          duration: 1000
        })
      }
    })
  },

  add: function () {
    console.log(this.data.tag)
    if (this.data.repeat == 1) {
      wx.showToast({
        icon: 'none',
        title: '请先扫码',
        duration: 1000
      })
    } else {
      if (this.data.tag == '还未输入') {
        wx.showToast({
          icon: 'none',
          title: '还未输入分类',
          duration: 1000
        })
      } else if (this.data.jia == '还未输入') {
        wx.showToast({
          icon: 'none',
          title: '还未输入位置',
          duration: 1000
        })
      } else {
        // 获取当前时间
        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        var n = timestamp * 1000;
        var date = new Date(n);
        var Y = date.getFullYear();
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
        var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        var h = date.getHours();
        var m = date.getMinutes();
        var s = date.getSeconds();
        //console.log("当前时间：" +Y+M+D+" "+h+":"+m+":"+s);  
        const db = wx.cloud.database()
        const book = db.collection('book_list')
        db.collection('book_list').add({
          data: {
            author: this.data.author,
            author_intro: this.data.author_intro,
            catalog: this.data.catalog,
            image: this.data.image,
            isbn: this.data.isbn,
            pages: this.data.pages,
            price: this.data.price,
            pubdate: this.data.pubdate,
            publisher: this.data.publisher,
            average: this.data.average,
            summary: this.data.summary,
            title: this.data.title,
            like: 0,
            borrow: '在馆可借阅',
            address: this.data.jia + this.data.row,
            tag: this.data.tag,
            colors: this.data.colors,
            translator: this.data.translator,
            inputdate: Y + "/" +M + "/" + D + " " + h + ":" + m + ":" + s
          }
        }).then(res => {
            console.log(res)
            wx.showToast({
              title: '增加成功',
              duration: 2000
            })
            this.setData({
              hd: true,
              repeat: '1',
              tag: '还未输入',
              jia: '还未输入',
              row: ''
            })
          }).catch(err => {
            console.log(err)
          })
      }
    }
  },
  //获取图片颜色
  chooseImg() {
    console.log('图片地址', this.data.imgPath)
    const that = this
    wx.getImageInfo({
      src: `${that.data.imgPath}`,
      success: (imgInfo) => {
        const poster = imgInfo.path
        console.log(imgInfo.path)
        let {
          width,
          height,
          imgPath
        } = imgInfo;
        let scale = 0.8 * this.screenWidth / Math.max(width, height);
        let canvasWidth = Math.floor(scale * width);
        let canvasHeight = Math.floor(scale * height);
        this.setData({
          imgInfo,
          canvasScale: scale,
          canvasWidth,
          canvasHeight
        });
        let quality = 1;
        console.log(quality);
        this.colorThief.getPalette({
          width: canvasWidth,
          height: canvasHeight,
          imgPath: imgInfo.path,
          colorCount: this.data.colorCount,
          quality
        }, (colors) => {
          console.log('colors', colors);
          if (colors) {
            colors = colors.map((color) => {
              return ('#' + rgbToHex(color[0], color[1], color[2]))
            })
            this.setData({
              colors,
              state: STATE_SUCCEED
            })
            console.log('colors_16', this.data.colors)
          }
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.colorThief = new ColorThief('imageHandler');
    wx.getSystemInfo({
      success: ({
        screenWidth
      }) => {
        this.screenWidth = screenWidth;
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})